import { login, userProfile, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: () => {
    return {
      // 保存token
      // 如果有就用持久化的token，如果没有就是空
      token: getToken() || '',
      userInfo: {}
    }
  },
  mutations: {
    setUserInfo(state, newUserInfo) {
      state.userInfo = newUserInfo
    },
    // 定义mutations修改token
    // mutations的名字(state, newToken)
    setToken(state, newToken) {
      // 保存token
      state.token = newToken
      // 调用封装好的函数，做持久化
      setToken(newToken)
    }
  },
  actions: {
    async userLogin(context, payload) {
      const res = await login(payload)
      context.commit('setToken', res.data)
    },
    async getUserProfile(context) {
      const res = await userProfile()
      const res1 = await getUserDetailById(res.data.userId)
      const obj = { ...res.data, ...res1.data }
      context.commit('setUserInfo', obj)
      return res
    },
    logout(context) {
      context.commit('setUserInfo', {})
      context.commit('setToken', '')
      context.commit('menu/resetMenu', null, { root: true })
      resetRouter()
    }
  }
}
